package org.rich.charlesmurphy.ui.renderers;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import org.ddevil.data.Data;
import org.windowkit.toolkit.widget.table.RecordTableModel;
import org.windowkit.toolkit.widget.table.render.AbstractTableCellRendererDecorator;

/**
 * Draws a bar in the cell, kind of like a bar graph.
 * Yo spliff,  where the weed at?
 */
public class BarRenderer extends AbstractTableCellRendererDecorator {

	private static final int DEFAULT_MAX = 100;
	private static final int DEFAULT_WIDTH = 40;
	private int currentCount = 0;
	private int max;
	private int barWidth;
	private Color color;

	/**
	 * @param barWidth
	 */
	public BarRenderer(Color color, int max, int barWidth) {
		this.max = max;
		this.barWidth = barWidth;
		this.color = color;
	}
	/**
	 * @param barWidth
	 */
	public BarRenderer(Color color, int max) {
		this(color, max, DEFAULT_WIDTH);
	}
	/**
	 * @param barWidth
	 */
	public BarRenderer(Color color) {
		this(color, DEFAULT_MAX, DEFAULT_WIDTH);
	}

	@Override
	protected void decorate(Component c, Data d, RecordTableModel model,
			JTable table, Object value, CellInfo cellInfo) {

		try {
			Number n = NumberFormat.getIntegerInstance().parse(value.toString());
			currentCount = n.intValue();
		} catch (ParseException e) {
			currentCount = 0;
		}
	}

	@Override
	protected TableCellRenderer createRenderer() {
		DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
			private static final long serialVersionUID = -8659484424575491492L;
			@Override
			public void paint(Graphics g) {
				super.paint(g);

				float c = currentCount;
				float m = max;
				float t = barWidth;
				float w = (c / m) * t;
				g.setColor(color);
				g.fillRect(2, 2, (int)w, 10);


			}
			@Override
			public void setValue(Object value) {
			    setText((value == null) ? "" : NumberFormat.getInstance().format(value));
			}
		};
		r.setHorizontalAlignment(SwingConstants.RIGHT);
		return r;
	}

	public void setBarWidth(int barWidth) {
		this.barWidth = barWidth;
	}

}
